package com.xiaoxu.intranetweb.mybatisplusSzappdb.timerTasks;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CWeightSheets;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.impl.CWeightSheetsServiceImpl;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
@Component
public class OrderedExcelToTextExporter {

    // 假设 service 已注入
    @Autowired
    private CWeightSheetsServiceImpl cWeightSheetsService;

    public void exportOrderedWeishtCo(String excelPath, String outputFilePath) throws Exception {
        List<Map<String, Object>> dataList = readExcelData(excelPath);

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {
            for (Map<String, Object> rowData : dataList) {
                // 打印当前处理行数
                int rowIndex = dataList.indexOf(rowData) + 2;
                System.out.println("处理第 " + rowIndex + " 行");
                // 判断必要字段是否为空
                if (rowData.get("类型") == null || rowData.get("车号") == null) {
                    writer.write("");
                    writer.newLine();
                    continue;
                }

System.out.println("类型: " + rowData.get("类型") + "，车号: " + rowData.get("车号").toString().replace("T", " ")+"，空车称重时间: " + rowData.get("空车称重时间").toString().replace("T", " ")+"，重车称重时间: " + rowData.get("重车称重时间")+"，总重: " + rowData.get("总重")+"，皮重: " + rowData.get("皮重")+"，净重计回空: " + rowData);
                QueryWrapper<CWeightSheets> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("WEISHT_PRODUCT", rowData.get("类型"))
                        .eq("WEISHT_TRUCKNO", rowData.get("车号"))
                        .eq("WEISHT_EMPTY_TM", rowData.get("空车称重时间").toString().replace("T", " "))
                        .eq("WEISHT_FULL_TM", rowData.get("重车称重时间").toString().replace("T", " "))
                        .eq("WEISHT_GROSS_WGHT", rowData.get("总重"))
                        .eq("WEISHT_TARE", rowData.get("皮重"))
                        .eq("WEISHT_NET_WGHT", rowData.get("净重计回空"));

                CWeightSheets result = cWeightSheetsService.getOne(queryWrapper);
                CWeightSheets cWeightSheets = new CWeightSheets();
                 cWeightSheets.setId(result.getId());
                cWeightSheets.setDownedID11(0);
                 cWeightSheetsService.updateById(cWeightSheets);
                if (result != null ) {
                    writer.write(result.getWeishtCo());
                } else {
                    writer.write(""); // 保持顺序
                }
                writer.newLine();
            }
        }
        System.out.println("✅ 数据已按原始顺序写入完成，路径: " + outputFilePath);
    }

    // 读取 Excel 数据的方法（保持顺序）
    // 读取 Excel 数据的方法（保持顺序）
    private List<Map<String, Object>> readExcelData(String filePath) throws Exception {
        List<Map<String, Object>> dataList = new ArrayList<>();
        FileInputStream fis = new FileInputStream(filePath);
        Workbook workbook = new XSSFWorkbook(fis);
        Sheet sheet = workbook.getSheetAt(0);

        String[] desiredColumns = {"类型", "车号", "空车称重时间", "重车称重时间", "总重", "皮重", "净重计回空"};
        Row headerRow = sheet.getRow(0);
        Map<String, Integer> columnMap = new HashMap<>();

        // 获取列索引
        for (int i = 0; i < headerRow.getLastCellNum(); i++) {
            Cell cell = headerRow.getCell(i);
            if (cell != null) {
                String header = cell.getStringCellValue();
                for (String col : desiredColumns) {
                    if (header.equals(col)) {
                        columnMap.put(col, i);
                    }
                }
            }
        }

        // 从第2行开始读取，保持原始顺序
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;

            Map<String, Object> rowData = new HashMap<>();
            for (String colName : desiredColumns) {
                int idx = columnMap.getOrDefault(colName, -1);
                if (idx == -1) {
                    rowData.put(colName, null);
                    continue;
                }

                Cell cell = row.getCell(idx);
                if (cell != null) {
                    switch (cell.getCellType()) {
                        case STRING:
                            String value = cell.getStringCellValue().trim();
                            if (colName.equals("空车称重时间") || colName.equals("重车称重时间")) {
                                try {
                                    // 使用两种常见格式尝试解析
                                    LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy/M/d H:mm:ss"));
                                    rowData.put(colName, LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy/M/d H:mm:ss")).toString().replace("T", " "));
                                } catch (Exception e) {
                                    try {
                                        rowData.put(colName, LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy/M/d H:mm")).toString().replace("T", " "));
                                    } catch (Exception ex) {
                                        rowData.put(colName, null);
                                    }
                                }
                            } else {
                                rowData.put(colName, value);
                            }
                            break;

                        case NUMERIC:
                            if (DateUtil.isCellDateFormatted(cell)) {
                                // 将 Date -> LocalDateTime
                                rowData.put(colName, cell.getDateCellValue().toInstant()
                                        .atZone(ZoneId.systemDefault())
                                        .toLocalDateTime());
                            } else {
                                rowData.put(colName, cell.getNumericCellValue());
                            }
                            break;
                    }
                } else {
                    rowData.put(colName, null);
                }
            }
            dataList.add(rowData);
        }

        workbook.close();
        fis.close();

        return dataList;
    }
}